package com.zsh.webfluxdemo1.service.impl;

import com.zsh.webfluxdemo1.entity.User;
import com.zsh.webfluxdemo1.service.UserService;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zsh
 * @Description
 * @create 2022-03-07 19:29
 */
@Repository
public class UserServiceImpl implements UserService {

    //创建map集合存储数据
    private final Map<Integer, User> users = new HashMap<>();
    public UserServiceImpl(){
        this.users.put(1,new User("zsh1","nan",17));
        this.users.put(2,new User("zsh2","nv",18));
        this.users.put(3,new User("zsh3","nan",19));
    }


    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {

        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> userMono) {
        return userMono.doOnNext(person -> {
            //想map中放值
            int id = users.size() +1;
            users.put(id,person);
        }).thenEmpty(Mono.empty());  //终止信号
    }
}
